package ru.picman;

/**
 * Each block instance holds the data for a block in the game.
 * 
 * @author Matthijs
 */
public class Block
{   
	
	/**
	 * Constructs a new block of the specified type (BLOCK_STONE 
	 * or BLOCK_WOOD). Stone blocks can actually break, but they're
	 * really strong, by default.
	 * 
	 * @param type The block type
	 */
	public Block(int type) {
		if (type < 0 || type > BLOCK_WOOD)
			throw new IllegalArgumentException("Invalid block type");
		this.imageID = blocks[type];
		this.damageLevel = 0;
		this.type = type;
		this.maxDamageLevel = (type == BLOCK_STONE ? 20 : 2);
	}
	
	/**
	 * Returns the current damage level.
	 * 
	 * @return The damage level
	 */
	public int getDamageLevel() {
		return damageLevel;
	}
	
	/**
	 * Returns the maximum damage level before the block breaks.
	 * 
	 * @return The maximum damage level
	 */
	public int getMaxDamageLevel() {
		return maxDamageLevel;
	}
	
	/**
	 * Returns the type of the block.
	 * 
	 * @return The block type
	 */
	public int getBlockType() {
		return type;
	}
	
	/**
	 * Returns the image id of the block. The image id refers to
	 * the image which visually represents the block.
	 * 
	 * @return the image id
	 */
	public int getImageID() {
		return imageID;
	}
	
	/**
	 * The block is hit. If this method is called, the damage level
	 * will be increased by one and if this level reached the max
	 * damage level the block will be {@link #destroy() destroyed}.
	 * If not, the image id may change.
	 */
	public void hit() {
		if (type == BLOCK_STONE)
			return;
		if (destroyed) {
			System.out.println("BADDDD hit when destroyed?");
			new Exception().printStackTrace();
			return;
		}
		++damageLevel;
		if (damageLevel == maxDamageLevel)
			destroy();
		else
			imageID = blocks[type+damageLevel];
	}
	
	/**
	 * The block is destroyed. Destroyed will be set to true. On the
	 * next world-tick the block will be completely removed from the
	 * game. This usually is 'instantly'.
	 */
	public void destroy() {
		destroyed = true;
	}
	
	/**
	 * Checks if the block is destroyed.
	 * 
	 * @return true if {@link #destroy()} has been called earlier
	 */
	public boolean isDestroyed() {
		return destroyed;
	}
	
	//
	
	private int imageID;
	private int damageLevel;
	private int maxDamageLevel;
	private boolean destroyed;
	
	private final int type;
	
	public static final int BLOCK_STONE = 0;
	public static final int BLOCK_WOOD = 1;
	
	private static final int[] blocks;
	
	static {
		blocks = new int[3];
		blocks[BLOCK_STONE] = R.drawable.block_stone;
		blocks[BLOCK_WOOD] = R.drawable.block_wood;
		blocks[BLOCK_WOOD+1] = R.drawable.block_wood2;
	}
	
}
